<route lang="jsonc">
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "服务管家"
  }
}
</route>

<script lang="ts" setup>
import type { V2NIMConversationType } from 'nim-web-sdk-ng/dist/esm/nim/src/V2NIMConversationService'
import type { V2NIMMessage } from 'nim-web-sdk-ng/dist/esm/nim/src/V2NIMMessageService'
import { onHide, onLoad, onShow, onUnload } from '@dcloudio/uni-app'

import { autorun } from 'mobx'
import { V2NIMConst } from 'nim-web-sdk-ng/dist/esm/nim'
import { isInitialized, updateActivityTime } from '@/utils/nimService'
import { getUniPlatform } from '../utils'
import { events, HISTORY_LIMIT } from '../utils/constants'
import { customSwitchTab } from '../utils/customNavigate'
import { t } from '../utils/i18n'
import { trackInit } from '../utils/reporter'
import { onMounted, onUnmounted, ref } from '../utils/transformVue'
import MessageInput from './message/message-input.vue'
import MessageList from './message/message-list.vue'

/** 未知 */
// V2NIM_CONVERSATION_TYPE_UNKNOWN = 0,
// /** 单聊 */
// V2NIM_CONVERSATION_TYPE_P2P = 1,
// /** 群聊 */
// V2NIM_CONVERSATION_TYPE_TEAM = 2,
// /** 超大群 */
// V2NIM_CONVERSATION_TYPE_SUPER_TEAM = 3
export interface YxReplyMsg {
  messageClientId: string
  scene: V2NIMConst.V2NIMConversationType
  from: string
  receiverId: string
  to: string
  idServer: string
  time: number
}

trackInit('ChatUIKit')

const title = ref('')

/** 会话ID */
const conversationId = uni.$UIKitStore.uiStore.selectedConversation

console.log('conversationId123123123123123', conversationId);

/** 会话类型 */
const conversationType
  = uni.$UIKitNIM.V2NIMConversationIdUtil.parseConversationType(
    conversationId,
  ) as unknown as V2NIMConversationType

console.log(conversationType, 'conversationTypeconversationTypeconversationTypeconversationType');

/** 对话方 */
const to
  = uni.$UIKitNIM.V2NIMConversationIdUtil.parseConversationTargetId(
    conversationId,
  ).replace('|', '')

// console.log('to123123123123123', to);

// 标记是否已经发送过热门专家消息
let hotExpertsMsgSent = false;

// 检查是否已经发送过热门专家消息
function checkHotExpertsMsgSent(): boolean {
  // 从本地存储中读取状态
  const status = uni.getStorageSync('hotExpertsMsgSent');
  return !!status;
}

// 设置热门专家消息已发送状态
function setHotExpertsMsgSent(sent: boolean): void {
  hotExpertsMsgSent = sent;
  // 保存到本地存储
  if (sent) {
    uni.setStorageSync('hotExpertsMsgSent', true);
  }
  else {
    uni.removeStorageSync('hotExpertsMsgSent');
  }
}

function sendHotExpertsMessage() {
  // 先检查本地存储中是否已经发送过
  if (checkHotExpertsMsgSent()) {
    console.log('本地存储显示已经发送过热门专家消息，不再重复发送');
    hotExpertsMsgSent = true;
    return;
  }

  if (hotExpertsMsgSent) {
    console.log('已经发送过热门专家消息，不再重复发送');
    return;
  }

  const customMsg = {
    type: 'hot-experts',
    data: {
      isShow: true,
    },
  }

  // 创建文本消息但标记为自定义类型
  const textMsg = uni.$UIKitNIM.V2NIMMessageCreator.createCustomMessage(
    JSON.stringify(customMsg),
    '100',
  )

  // 手动设置消息类型为自定义
  // @ts-expect-error 类型不匹配，但实际可用
  textMsg.messageType = V2NIMConst.V2NIMMessageType.V2NIM_MESSAGE_TYPE_CUSTOM

  uni.$UIKitStore.msgStore.sendMessageActive({
    // @ts-expect-error 类型不匹配，但实际可用
    msg: textMsg,
    conversationId,
  }).then(() => {
    console.log('热门专家消息发送成功');
    // 标记为已发送并保存到本地存储
    setHotExpertsMsgSent(true);
  }).catch((error) => {
    console.error('热门专家消息发送失败:', error);
  });
}

// 重置热门专家消息状态
function resetHotExpertsStatus() {
  console.log('重置热门专家消息状态');
  setHotExpertsMsgSent(false);
}

const isH5 = getUniPlatform() === 'web'

/** 处理uni-popup 引起的滚动穿透 */
const moveThrough = ref(false)

/** 回到会话列表 */
function backToConversation() {
  customSwitchTab({
    url: '/pages/Conversation/index',
  })
}

/** 是否需要显示群组消息已读未读，默认 false */
const teamManagerVisible = uni.$UIKitStore.localOptions.teamMsgReceiptVisible

/** 是否需要显示 p2p 消息、p2p会话列表消息已读未读，默认 false */
const p2pMsgReceiptVisible = uni.$UIKitStore.localOptions.p2pMsgReceiptVisible

let isMounted = false

const loadingMore = ref(false)

/** 是否还有更多历史消息 */

const noMore = ref(false)

/** 消息列表 */
const msgs = ref<V2NIMMessage[]>([])

/** 回复消息map，用于回复消息的解析处理 */
const replyMsgsMap = ref<Record<string, V2NIMMessage>>()

/** 解散群组回调 */
function onTeamDismissed(data: any) {
  if (data.teamId === to) {
    uni.showModal({
      content: t('onDismissTeamText'),
      showCancel: false,
      success(data) {
        if (data.confirm) {
          backToConversation()
        }
      },
    })
  }
}

/** 自己主动离开群组或被管理员踢出回调 */
function onTeamLeft(data: any) {
  uni
    .showToast({
      title: t('onRemoveTeamText'),
      icon: 'success',
      duration: 1000,
    })
    .then(() => {
      backToConversation()
    })
}

/** 收到新消息 */
function onReceiveMessages(msgs: V2NIMMessage[]) {
  const routes = getCurrentPages()
  const curRoute = routes[routes.length - 1].route

  // 不是当前用户的其他端发送的消息且是当前会话的未读消息，才发送已读回执
  if (
    msgs.length
    && !msgs[0]?.isSelf
    && msgs[0].conversationId === conversationId
    && curRoute?.includes('Chat/index')
  ) {
    handleMsgReceipt(msgs)
  }
  uni.$emit(events.ON_SCROLL_BOTTOM, msgs)
}

/** 处理收到消息的已读回执 */
function handleMsgReceipt(msg: V2NIMMessage[]) {
  if (
    msg[0].conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P
    && p2pMsgReceiptVisible
  ) {
    uni.$UIKitStore.msgStore.sendMsgReceiptActive(msg[0])
  }
  else if (
    msg[0].conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_TEAM
    && teamManagerVisible
  ) {
    uni.$UIKitStore.msgStore.sendTeamMsgReceiptActive(msg)
  }
}

/** 处理历史消息的已读未读 */
function handleHistoryMsgReceipt(msgs: V2NIMMessage[]) {
  /** 如果是单聊 */
  if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P
    && p2pMsgReceiptVisible
  ) {
    const myUserAccountId = uni.$UIKitNIM.V2NIMLoginService.getLoginUser()
    const othersMsgs = msgs
      .filter(
        (item: V2NIMMessage) =>
          // eslint-disable-next-line ts/ban-ts-comment
          // @ts-ignore
          !['beReCallMsg', 'reCallMsg'].includes(item.recallType || ''),
      )
      .filter((item: V2NIMMessage) => item.senderId !== myUserAccountId)

    /** 发送单聊消息已读回执 */
    if (othersMsgs.length > 0) {
      uni.$UIKitStore.msgStore.sendMsgReceiptActive(othersMsgs?.[0])
    }

    /** 如果是群聊 */
  }
  else if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_TEAM
    && teamManagerVisible
  ) {
    const myUserAccountId = uni.$UIKitNIM.V2NIMLoginService.getLoginUser()
    const myMsgs = msgs
      .filter(
        (item: V2NIMMessage) =>
          // eslint-disable-next-line ts/ban-ts-comment
          // @ts-ignore
          !['beReCallMsg', 'reCallMsg'].includes(item.recallType || ''),
      )
      .filter((item: V2NIMMessage) => item.senderId === myUserAccountId)

    uni.$UIKitStore.msgStore.getTeamMsgReadsActive(myMsgs, conversationId)

    // 发送群消息已读回执
    // sdk 要求 一次最多传入 50 个消息对象
    const othersMsgs = msgs
      .filter(
        (item: V2NIMMessage) =>
          // eslint-disable-next-line ts/ban-ts-comment
          // @ts-ignore
          !['beReCallMsg', 'reCallMsg'].includes(item.recallType || ''),
      )
      .filter((item: V2NIMMessage) => item.senderId !== myUserAccountId)

    if (othersMsgs.length > 0 && othersMsgs.length < 50) {
      uni.$UIKitStore.msgStore.sendTeamMsgReceiptActive(othersMsgs)
    }
  }
}

/** 拉取历史消息 */
async function getHistory(endTime: number, lastMsgId?: string) {
  try {
    if (noMore.value) {
      return []
    }
    if (loadingMore.value) {
      return []
    }
    loadingMore.value = true
    if (conversationId) {
      const historyMsgs = await uni.$UIKitStore.msgStore.getHistoryMsgActive({
        conversationId,
        endTime,
        lastMsgId,
        limit: HISTORY_LIMIT,
      })
      // 在点击会话时，去获取并更新 pin 和 msg 信息。
      await uni.$UIKitStore.msgStore.getPinnedMessageListActive(conversationId)

      loadingMore.value = false
      if (historyMsgs.length < HISTORY_LIMIT) {
        noMore.value = true
      }

      // 处理历史消息中的热门专家消息，只显示最新的一条
      const hotExpertMessages = historyMsgs.filter((msg) => {
        try {
          if (!msg.text)
            return false;
          const customData = JSON.parse(msg.text);
          return customData.type === 'hot-experts';
        }
        catch (e) {
          return false;
        }
      });

      console.log('历史消息中热门专家消息数量:', hotExpertMessages.length);

      // 如果有多条热门专家消息，只保留最新的一条
      if (hotExpertMessages.length > 1) {
        // 按创建时间排序，找出最新的一条
        const latestHotExpertMsg = hotExpertMessages.reduce((latest, current) =>
          current.createTime > latest.createTime ? current : latest,
        );

        console.log('历史消息中最新的热门专家消息:', latestHotExpertMsg);

        // 将其他热门专家消息的isShow设置为false
        hotExpertMessages.forEach((msg) => {
          if (msg.createTime !== latestHotExpertMsg.createTime) {
            try {
              const customData = JSON.parse(msg.text);
              customData.data.isShow = false;
              // 修改消息的text内容
              msg.text = JSON.stringify(customData);
            }
            catch (e) {
              console.error('修改历史热门专家消息失败:', e);
            }
          }
        });
      }

      // 过滤掉不显示的热门专家消息
      const filteredHistoryMsgs = historyMsgs.filter((msg) => {
        try {
          if (!msg.text)
            return true;
          const customData = JSON.parse(msg.text);
          if (customData.type === 'hot-experts' && customData.data.isShow === false) {
            return false; // 过滤掉不显示的热门专家消息
          }
          return true;
        }
        catch (e) {
          return true;
        }
      });

      // 消息已读未读相关
      handleHistoryMsgReceipt(filteredHistoryMsgs)
      return filteredHistoryMsgs
    }
  }
  catch (error) {
    loadingMore.value = false
    throw error
  }
}

/** 加载更多消息 */
function loadMoreMsgs(lastMsg: V2NIMMessage) {
  getHistory(lastMsg.createTime, lastMsg.messageServerId).then(
    (res: V2NIMMessage[]) => {
      // 发送历史消息加载成功的事件通知
      console.log(res, '加载更多消息');

      if (res && res.length > 0) {
        uni.$emit(`${events.GET_HISTORY_MSG}_SUCCESS`, res)
      }

      if (res?.[0]) {
        // uni.pageScrollTo 微信小程序指定滚动位置不起作用
      }
    },
  )
}

/** 监听当前聊天页面的会话类型 */
const conversationTypeWatch = autorun(() => {
  // 如果是单聊
  if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P
  ) {
    title.value = uni.$UIKitStore.uiStore.getAppellation({ account: to })
    // 如果是群聊
  }
  else if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_TEAM
  ) {
    const team = uni.$UIKitStore.teamStore.teams.get(to)
    const subTitle = `(${team?.memberCount || 0})`
    title.value = (team?.name || '') + subTitle
  }
})

/** 监听连接状态 */
const connectedWatch = autorun(async () => {
  const connectStatus = uni.$UIKitStore.connectStore.connectStatus;
  const loginStatus = uni.$UIKitStore.connectStore.loginStatus;

  console.log('云信连接状态:', connectStatus, '登录状态:', loginStatus);

  // 连接断开时，重置热门专家消息发送状态
  if (connectStatus === V2NIMConst.V2NIMConnectStatus.V2NIM_CONNECT_STATUS_DISCONNECTED) {
    console.log('云信SDK连接断开，重置热门专家消息状态');
    resetHotExpertsStatus();
    return;
  }

  // 等待重连状态 - 移除手动重连逻辑，因为NIMService已经处理了token刷新
  if (connectStatus === V2NIMConst.V2NIMConnectStatus.V2NIM_CONNECT_STATUS_WAITING) {
    console.log('云信SDK正在等待重连...');
    // 不需要手动处理，SDK的tokenProvider会自动处理
    return;
  }

  if (connectStatus === V2NIMConst.V2NIMConnectStatus.V2NIM_CONNECT_STATUS_CONNECTED) {
    if (loginStatus === V2NIMConst.V2NIMLoginStatus.V2NIM_LOGIN_STATUS_LOGINED) {
      // 加载历史记录
      getHistory(Date.now()).then(() => {
        if (!isMounted) {
          uni.$emit(events.ON_SCROLL_BOTTOM)
          isMounted = true;

          // 只在首次连接成功时发送热门专家消息
          if (!checkHotExpertsMsgSent()) {
            console.log('云信SDK连接成功，发送热门专家消息');
            sendHotExpertsMessage();
          }
          else {
            console.log('已经发送过热门专家消息，不再重复发送');
          }
        }
      })
    }
    else {
      // 登录状态异常，重置热门专家消息状态
      console.log('云信SDK已连接但未登录，重置热门专家消息状态');
      resetHotExpertsStatus();
    }
  }
})
/** 动态更新消息 */
const msgsWatch = autorun(() => {
  // 这里需要 Clone，否则 pinState 更新了，对应的消息展示不会重新渲染
  const messages = [...uni.$UIKitStore.msgStore.getMsg(conversationId)]
  console.log('获取到的消息列表:', messages);
  console.log('当前会话ID:', conversationId);

  // 查找所有热门专家消息
  const hotExpertMessages = messages.filter((msg) => {
    try {
      if (!msg.text)
        return false;
      const customData = JSON.parse(msg.text);
      return customData.type === 'hot-experts';
    }
    catch (e) {
      return false;
    }
  });

  console.log('热门专家消息数量:', hotExpertMessages.length);

  // 如果有多条热门专家消息，只保留最新的一条
  if (hotExpertMessages.length > 1) {
    // 按创建时间排序，找出最新的一条
    const latestHotExpertMsg = hotExpertMessages.reduce((latest, current) =>
      current.createTime > latest.createTime ? current : latest,
    );

    console.log('最新的热门专家消息:', latestHotExpertMsg);

    // 将其他热门专家消息的isShow设置为false
    hotExpertMessages.forEach((msg) => {
      if (msg.createTime !== latestHotExpertMsg.createTime) {
        try {
          const customData = JSON.parse(msg.text);
          customData.data.isShow = false;
          // 修改消息的text内容
          msg.text = JSON.stringify(customData);
        }
        catch (e) {
          console.error('修改热门专家消息失败:', e);
        }
      }
    });
  }

  if (messages.length !== 0) {
    // 过滤掉不显示的热门专家消息
    const filteredMessages = messages.filter((msg) => {
      try {
        if (!msg.text)
          return true;
        const customData = JSON.parse(msg.text);
        if (customData.type === 'hot-experts' && customData.data.isShow === false) {
          return false; // 过滤掉不显示的热门专家消息
        }
        return true;
      }
      catch (e) {
        return true;
      }
    });

    msgs.value = filteredMessages;
    console.log('过滤后的消息列表:', msgs.value);
  }

  // 遍历所有消息，找出被回复消息，储存在map中
  if (messages.length !== 0) {
    const _replyMsgsMap: any = {}
    const reqMsgs: YxReplyMsg[] = []
    const messageClientIds: Record<string, string> = {}
    msgs.value.forEach((msg) => {
      if (msg.serverExtension) {
        try {
          // yxReplyMsg 存储着被回复消息的相关消息
          const { yxReplyMsg } = JSON.parse(msg.serverExtension)
          if (yxReplyMsg) {
            // 从消息列表中找到被回复消息，replyMsg 为被回复的消息
            const replyMsg = msgs.value.find(
              item => item.messageClientId === yxReplyMsg.idClient,
            )
            // 如果直接找到，存储在map中
            if (replyMsg) {
              _replyMsgsMap[msg.messageClientId] = replyMsg
              // 如果没找到，说明被回复的消息可能有三种情况：1.被删除 2.被撤回 3.不在当前消息列表中（一次性没拉到，在之前的消息中）
            }
            else {
              _replyMsgsMap[msg.messageClientId] = { messageClientId: 'noFind' }
              const {
                scene,
                from,
                to,
                idServer,
                messageClientId,
                time,
                receiverId,
              } = yxReplyMsg

              if (
                scene
                && from
                && to
                && idServer
                && messageClientId
                && time
                && receiverId
              ) {
                reqMsgs.push({
                  scene,
                  from,
                  to,
                  idServer,
                  messageClientId,
                  time,
                  receiverId,
                })
                messageClientIds[idServer] = msg.messageClientId
              }
            }
          }
        }
        catch {}
      }
    })

    if (reqMsgs.length > 0) {
      // 从服务器拉取被回复消息, 但是有频率控制
      uni.$UIKitNIM.V2NIMMessageService.getMessageListByRefers(
        // eslint-disable-next-line ts/ban-ts-comment
        // @ts-ignore
        reqMsgs.map(item => ({
          senderId: item.from,
          receiverId: item.receiverId,
          messageClientId: item.messageClientId,
          messageServerId: item.idServer,
          createTime: item.time,
          conversationType: item.scene,
          conversationId: item.to,
        })),
      )
        .then((res) => {
          if (res?.length > 0) {
            res.forEach((item) => {
              if (item.messageServerId) {
                _replyMsgsMap[messageClientIds[item.messageServerId]] = item
              }
            })
          }
          replyMsgsMap.value = { ..._replyMsgsMap }
        })
        .catch(() => {
          replyMsgsMap.value = { ..._replyMsgsMap }
        })
    }
    else {
      replyMsgsMap.value = { ..._replyMsgsMap }
    }
  }

  // 当聊天消息小于6条时，由于页面被键盘撑起，导致已经发出的消息不可见，所以需要隐藏键盘
  if (messages.length < 6) {
    uni.hideKeyboard()
  }
})

/** 设置页面标题 */
function setNavTitle() {
  if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P
  ) {
    title.value = uni.$UIKitStore.uiStore.getAppellation({ account: to })
  }
  else if (
    conversationType
    === V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_TEAM
  ) {
    const team = uni.$UIKitStore.teamStore.teams.get(to)
    const subTitle = `(${team?.memberCount || 0})`
    title.value = (team?.name || '') + subTitle
  }
}

onShow(() => {
  console.log('用户回到聊天页面，触发聊天活动');
  setNavTitle()
  scrollToBottom()

  // 用户回到聊天页面算作聊天活动
  uni.$emit('chatActivity');

  // 从其他页面返回到聊天页时，可能使用的是 uni.navigateBack，此时不会触发onload等事件，但此时需要将收到的新消息发送已读未读
  if (msgs.value.length) {
    const _msgs = [...msgs.value].reverse()
    handleHistoryMsgReceipt(_msgs)
  }
})

/** 滚动到底部 */
function scrollToBottom() {
  const timer = setTimeout(() => {
    uni.$emit(events.ON_SCROLL_BOTTOM)
    clearTimeout(timer)
  }, 300)
}

/** 设置调试模式 */
function setDebugMode(enabled: boolean) {
  if (enabled) {
    uni.setStorageSync('debug_mode', true);
    uni.showToast({
      title: '调试模式已开启',
      icon: 'none',
      duration: 2000,
    });
  }
  else {
    uni.removeStorageSync('debug_mode');
    uni.showToast({
      title: '调试模式已关闭',
      icon: 'none',
      duration: 2000,
    });
  }
}

/** 触发用户活动事件 */
function triggerUserActivity() {
  console.log('聊天页面触发用户活动事件');

  // 发送用户活动事件
  uni.$emit('userActivity');

  // 直接更新活动时间
  updateActivityTime();

  // 简化调试模式逻辑 - 只在调试模式下显示提示
  if (uni.getStorageSync('debug_mode')) {
    uni.showToast({
      title: '活动时间已更新',
      icon: 'none',
      duration: 1000,
    });

    // 调试模式下的双击切换逻辑
    const now = Date.now();
    const lastTap = uni.getStorageSync('last_tap_time') || 0;

    if (now - lastTap < 500) {
      const tapCount = (uni.getStorageSync('tap_count') || 0) + 1;
      uni.setStorageSync('tap_count', tapCount);

      if (tapCount >= 5) {
        setDebugMode(false); // 关闭调试模式
        uni.setStorageSync('tap_count', 0);
      }
    }
    else {
      uni.setStorageSync('tap_count', 1);
    }

    uni.setStorageSync('last_tap_time', now);
  }
}

onLoad(() => {
  uni.$on(events.HANDLE_MOVE_THROUGH, (flag) => {
    moveThrough.value = flag
  })

  // 初始化热门专家消息状态
  hotExpertsMsgSent = checkHotExpertsMsgSent();
  console.log('页面加载，热门专家消息状态:', hotExpertsMsgSent ? '已发送' : '未发送');
})

// 定期检查会话状态
let sessionCheckTimer: number | null = null;

function startSessionCheck() {
  // 先清除可能存在的定时器
  if (sessionCheckTimer) {
    clearTimeout(sessionCheckTimer);
    sessionCheckTimer = null;
  }

  function checkSession() {
    console.log('定期检查会话状态...');

    // 检查nimService是否还处于初始化状态
    if (!isInitialized()) {
      console.log('检测到NIMService未初始化，停止会话检查');
      return;
    }

    // 移除自动触发活动，只做状态检查
    // 不再调用 triggerUserActivity()，避免人为延长会话

    // 设置下一次检查
    sessionCheckTimer = setTimeout(() => {
      checkSession();
    }, 60000); // 60秒检查一次
  }

  // 启动第一次检查 - 延迟启动，避免页面加载时立即触发
  sessionCheckTimer = setTimeout(checkSession, 60000);
  console.log('会话检查定时器已启动');
}

onMounted(() => {
  setNavTitle()
  scrollToBottom()

  // 开始定期检查会话状态
  startSessionCheck();

  // 监听会话过期事件
  uni.$on('sessionExpired', (data) => {
    console.log('收到会话过期通知:', data);
    uni.showModal({
      title: '会话已过期',
      content: '您的会话已过期，请重新进入聊天',
      showCancel: false,
      confirmText: '确定',
      success: () => {
        uni.navigateBack();
      },
    });
  });

  // 简化NIM初始化检查 - 因为在打开页面前已经通过openWenWenPage确保了初始化
  if (!uni.$UIKitNIM || !uni.$UIKitStore) {
    console.error("NIM未初始化，返回上一页");
    uni.showToast({
      title: '系统未准备就绪，请重新进入',
      icon: 'none',
      duration: 2000,
    });

    // 延迟返回，让用户看到提示
    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
    return;
  }

  // 检查nimService的初始化状态
  if (!isInitialized()) {
    console.error("NIMService未初始化，返回上一页");
    uni.showToast({
      title: '连接已断开，请重新进入',
      icon: 'none',
      duration: 2000,
    });

    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
    return;
  }

  /** 收到消息 */
  uni.$UIKitNIM.V2NIMMessageService.on(
    'onReceiveMessages',
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-ignore
    onReceiveMessages,
  )
  /** 解散群组回调 */
  uni.$UIKitNIM.V2NIMTeamService.on('onTeamDismissed', onTeamDismissed)
  /** 自己主动离开群组或被管理员踢出回调 */
  uni.$UIKitNIM.V2NIMTeamService.on('onTeamLeft', onTeamLeft)

  uni.$on(events.GET_HISTORY_MSG, loadMoreMsgs)
})

onUnmounted(() => {
  uni.$UIKitNIM.V2NIMTeamService.off('onTeamDismissed', onTeamDismissed)
  uni.$UIKitNIM.V2NIMTeamService.off('onTeamLeft', onTeamLeft)
  uni.$UIKitNIM.V2NIMMessageService.off(
    'onReceiveMessages',
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-ignore
    onReceiveMessages,
  )

  uni.$off(events.GET_HISTORY_MSG, loadMoreMsgs)
  /** 移除store的数据监听 */
  connectedWatch()
  msgsWatch()
  conversationTypeWatch()

  // 清除会话检查定时器
  if (sessionCheckTimer) {
    console.log('清除会话检查定时器');
    clearTimeout(sessionCheckTimer);
    sessionCheckTimer = null;
  }
})

onHide(() => {
  console.log('聊天页面隐藏，但会话检查继续运行');
  uni.hideKeyboard()

  // 用户离开聊天页面，标记为非活跃状态
  // 但保持会话检查定时器运行，这样会话会在10分钟后正常过期
})

onUnload(() => {
  uni.$off(events.CONFIRM_FORWARD_MSG)
  uni.$off(events.CANCEL_FORWARD_MSG)

  // 清除会话过期监听
  uni.$off('sessionExpired')

  // 清除会话检查定时器
  if (sessionCheckTimer) {
    clearTimeout(sessionCheckTimer)
    sessionCheckTimer = null
  }

  // 不再重置热门专家消息状态，确保重新进入页面时不会再次发送
  console.log('页面卸载，保持热门专家消息状态');
  // 不调用 setHotExpertsMsgSent(false)，保持状态
})
</script>

<template>
  <!-- 处理滚动穿透  此为官方推荐做法 https://uniapp.dcloud.net.cn/component/uniui/uni-popup.html#%E4%BB%8B%E7%BB%8D -->
  <div :class="isH5 ? 'msg-page-wrapper-h5' : 'msg-page-wrapper'" @tap="triggerUserActivity">
    <div class="msg-alert">
      <!-- <NetworkAlert /> -->
    </div>
    <div :class="isH5 ? 'msg-wrapper-h5' : 'msg-wrapper'">
      <MessageList
        :conversation-type="conversationType"
        :to="to"
        :msgs="msgs"
        :loading-more="loadingMore"
        :no-more="noMore"
        :reply-msgs-map="replyMsgsMap"
      />
    </div>
    <div style="height: 'auto'">
      <MessageInput
        :reply-msgs-map="replyMsgsMap"
        :conversation-type="conversationType"
        :to="to"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
page {
  height: 100%;
  overflow: hidden;
}

.msg-page-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.msg-page-wrapper-h5 {
  width: 100%;
  height: 100%;
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}

.msg-alert {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: auto;
  z-index: 1;
}

.msg-wrapper {
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
  flex: 1;
}

.msg-wrapper-h5 {
  width: 100%;
  height: 100%;
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
}

.msg-wrapper > message-list {
  height: 100%;
}
</style>
